//=========================================================================
// Copyright (C) 2023 The C++ Component Model(COMO) Open Source Project
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//      http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//=========================================================================

#include "checksum.h"

Integer CheckCOMO_ZMQ_RPC_MSG(const unsigned char *input_bytes, size_t num_bytes)
{
    if (num_bytes < (sizeof(COMO_ZMQ_RPC_MSG_HEAD) + sizeof(COMO_ZMQ_RPC_MSG_BODY)))
        return -1;

    COMO_ZMQ_RPC_MSG_HEAD *funCodeAndCRC64 = reinterpret_cast<COMO_ZMQ_RPC_MSG_HEAD *>(input_bytes);

    const unsigned char *buf = input_bytes + sizeof(COMO_ZMQ_RPC_MSG_HEAD);
    size_t bufSize = num_bytes - sizeof(COMO_ZMQ_RPC_MSG_HEAD);

    COMO_ZMQ_RPC_MSG_BODY *body = reinterpret_cast<COMO_ZMQ_RPC_MSG_BODY *>(buf);

    Long crc64 = crc_64_ecma(buf, bufSize);
    Long crcTmp = funCodeAndCRC64->crc64;
    funCodeAndCRC64->crc64 = 0;
    crc64 = update_crc_64_ecma_bytes(crc64,
                            reinterpret_cast<const unsigned char *>(funCodeAndCRC64),
                            sizeof(COMO_ZMQ_RPC_MSG_HEAD));

    if ((crcTmp != crc64) || (funCodeAndCRC64->msgSize != bufSize)) {
        return -2;
    }

    if (RPC_MAGIC_NUMBER != body->RPC_MAGIC_NUMBER)
        return -3;

    return 0;
}

Integer GenCOMO_ZMQ_RPC_MSG(unsigned char *input_bytes, size_t num_bytes)
{
    const char *TEST_MSG = "Tongji University";

    if (num_bytes < (sizeof(COMO_ZMQ_RPC_MSG_HEAD) + sizeof(COMO_ZMQ_RPC_MSG_BODY) + strlen(TEST_MSG) + 1))
        return -1;

    COMO_ZMQ_RPC_MSG_HEAD *funCodeAndCRC64 = reinterpret_cast<COMO_ZMQ_RPC_MSG_HEAD *>(input_bytes);

    const unsigned char *buf = input_bytes + sizeof(COMO_ZMQ_RPC_MSG_HEAD);
    size_t bufSize = num_bytes - sizeof(COMO_ZMQ_RPC_MSG_HEAD);

    COMO_ZMQ_RPC_MSG_BODY *body = reinterpret_cast<COMO_ZMQ_RPC_MSG_BODY *>(buf);

    // generate an random COMO_ZMQ_RPC Message
    funCodeAndCRC64->hChannel = 0;
    funCodeAndCRC64->eCode = 0;
    funCodeAndCRC64->crc64 = 0;
    funCodeAndCRC64->msgSize = strlen(TEST_MSG) + 1;
    strcpy(buf, TEST_MSG);

    Long crc64 = crc_64_ecma(buf, bufSize);
    funCodeAndCRC64->crc64 = update_crc_64_ecma_bytes(crc64,
                            reinterpret_cast<const unsigned char *>(funCodeAndCRC64),
                            sizeof(COMO_ZMQ_RPC_MSG_HEAD));

    body->RPC_MAGIC_NUMBER = RPC_MAGIC_NUMBER;

    return 0;
}

#endif // __CZMQUTILS_H__
